#include <iostream>
#include <pthread.h>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <thread>
#include <vector>
#include <cstring>
#include <cstdio>
using namespace std;
#define NUM 3

//int *p = NULL;

__thread int g_val = 100;
__thread int number = 0;
struct threadData
{
    string threadname;
};
string toHex(pthread_t tid)
{
    char buffer[128];
    snprintf(buffer, sizeof(buffer), "0x%x", tid);
    return buffer;
}
void* threadRoutine(void* args)
{
    pthread_detach(pthread_self());
    //int test_i = 0;
    threadData *td = static_cast<threadData*>(args);
    number = pthread_self();
    // if(td->threadname == "thread-2")
    // {
    //     p = &test_i;
    // }
    int i = 0;
    while(i < 10)
    {
        //cout << "number: " << number << ", pid: " << getpid() << endl;
        printf("number: 0x%x, pid: %d\n", number, getpid());
        //cout << "pid: " << getpid() << ", tid : " << toHex(number) << ", threadname : " << td->threadname << ", g_val: " << g_val << ", &g_val: " << &g_val << endl;         
        // << ", test_i: " << test_i << ", &test_i: " << &test_i << endl;
        sleep(1);
        i++;
        g_val++;
      //  test_i++;
    }

    delete td;
    return nullptr;
}


void InitThreadData(threadData* td, int number)
{
    td->threadname = "thread-" + to_string(number); 
}

int main()
{
    vector<pthread_t> tids;
    for(int i = 0; i < NUM; i++)
    {
        //注意这种方式不可以，因为都在主线程的栈中定义的变量。一旦for循环每循环一次
        //td也要随之销毁掉。这里传入的全部都是野指针了。
        // threadData td;
        // td.threadname = "";
        // td.tid = "";
        pthread_t tid;
        threadData *td = new threadData;
        InitThreadData(td, i);
        pthread_create(&tid, nullptr, threadRoutine, td);
        tids.push_back(tid);
    }
    usleep(100000); //确保复制成功
    // cout << "main thread get a thread local value, val: " << *p << ", &val: " << p << endl;   

    // for(auto i : tids)
    // {
    //     pthread_detach(i);
    // }

    for(int i = 0; i < tids.size(); i++) 
    {
        int n = pthread_join(tids[i], nullptr);
        printf("n = %d, who = 0x%x, why: %s\n", n , tids[i], strerror(n));
    }
    //sleep(10);
    return 0;
}